"""
Case Type   : 系统内部使用工具
Case Name   : 在减容开始之后立即使用gs_om进行重启数据库
Create At   : 2022/03/03
Owner       : opentestcase018
Description :
    1.一主两备在减容备1开始后立即使用gs_om进行重启数据库
    2.恢复环境
Expect      :
    1.备机减容失败
    2.清理成功
History     :
    2022-5-17 opentestcase039 优化用例，根据自动化连跑要求，修改用例为在源库上减容
    2022-7-1 opentestcase039 优化用例，减小线程间启动时间，将重启改为在主机操作，减小对环境性能要求
    2022-9-13 opentestcase039 优化用例，由于研发代码变更，修改断言
    2022-9-29 opentestcase039 优化用例，优化断言信息
"""
import os
import time
import unittest
from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
primary_sh = CommonSH('PrimaryDbUser')
Constant = Constant()


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.standby1_root_node = Node('Standby1Root')
        self.standby1_node = Node('Standby1DbUser')
        self.standby2_root_node = Node('Standby2Root')
        self.standby2_node = Node('Standby2DbUser')
        self.u_name = self.primary_node.ssh_user
        self.pri_host = self.primary_node.db_host
        self.sta1_host = self.standby1_root_node.db_host
        self.sta2_host = self.standby2_root_node.db_host
        self.ssh_file = os.path.join('/home', self.u_name, 'hostfile')
        check_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_om -t status --detail;'
        self.log.info(check_cmd)
        check_res = self.primary_node.sh(check_cmd).result()
        self.log.info(check_res)

    def test_gs_dropnode(self):
        text = '----step1:在对备1减容开始后立即重启数据库 expect:减容失败----'
        self.log.info(text)
        self.log.info('构建减容命令shell脚本前置条件')
        drop_cmd = f'gs_dropnode -U {self.u_name} -G {self.u_name} ' \
                   f'-h {self.sta1_host}'
        self.log.info(drop_cmd)
        global shell_path
        shell_path = os.path.join('/', 'home', f'{self.u_name}', 'dropnode.sh')
        shell_cmd = f'touch {shell_path};echo -e {drop_cmd} > {shell_path};' \
                    f'chmod 755 {shell_path};cat {shell_path}'
        self.log.info(shell_cmd)
        pri_shell_res = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(pri_shell_res)
        self.log.info('对备1执行减容操作')
        drop_cmd = f'''source {macro.DB_ENV_PATH}
                   expect <<EOF
                   set timeout 200 
                   spawn {shell_path}
                   expect "(yes/no)?"
                   send "yes\\n"
                   expect eof\n''' + '''EOF'''
        session_1 = ComThread(self.common.get_sh_result, args=(
            self.primary_node, drop_cmd,))
        session_1.setDaemon(True)
        self.log.info('在备1减容开始后执行重启数据库操作')
        restart_cmd = f'source {macro.DB_ENV_PATH};' \
                      f'gs_om -t restart;'
        session_2 = ComThread(self.common.get_sh_result, args=(
            self.primary_node, restart_cmd,))
        session_2.setDaemon(True)
        session_1.start()
        time.sleep(0.01)
        session_2.start()
        self.log.info('备1减容结果')
        session_1.join(120)
        session_1_result = session_1.get_result()
        self.log.info(session_1_result)
        self.log.info('数据库重启结果')
        session_2.join(120)
        session_2_result = session_2.get_result()
        self.log.info(session_2_result)
        self.log.info('断言备1减容及数据库重启结果')
        self.assertNotIn('Success to drop the target nodes',
                         session_1_result, '备2减容错误')
        self.assertIn(Constant.START_SUCCESS_MSG, session_2_result,
                      '数据库重启失败')
        self.log.info('检查减容失败信息是否写入日志')
        log_path = os.path.join(f'{macro.GAUSSDB_LOG_PATH}', f'{self.u_name}',
                                'om', 'gs_dropnode*.log')
        log_res = self.primary_root_node.sh(f'cat {log_path}').result()
        self.log.info(log_res)
        self.log.info('检查数据库是否减容')
        check_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_om -t status --detail;'
        self.log.info(check_cmd)
        check_res = self.primary_node.sh(check_cmd).result()
        self.log.info(check_res)
        check_lis = [self.pri_host, self.sta1_host, self.sta2_host]
        for info in check_lis:
            self.assertIn(info, check_res, '数据库状态检查失败')

    def tearDown(self):
        text = "----step2:恢复环境，清理文件 expect:成功----"
        self.log.info(text)
        del_cmd = f"rm -rf {shell_path}"
        self.log.info(del_cmd)
        del_res = self.primary_root_node.sh(del_cmd).result()
        self.log.info(del_res)
        self.assertEqual('', del_res, '文件删除失败')
        self.log.info(f'----{os.path.basename(__file__)} finish----')
